package com.example.demo.config.task;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author huangke
 * @description default
 * @date 2020/12/23
 */
@Configuration
@EnableConfigurationProperties(FirstCustomerAsyncConfig.Customer2CustomerTaskProperties.class)
public class FirstCustomerAsyncConfig {
    @Resource
    private CustomerTaskExecutorBuilder builder;

    @Bean(name = "firstCustomerExecutor")
    public Executor asyncServiceExecutor(@Qualifier("customer2Properties") CustomerTaskExecutorBuilder.CustomerTaskExecutorProperties properties) {
        ThreadPoolTaskExecutor executor = builder.taskExecutorBuilder(properties).build();
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        /**
         * ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
         * ThreadPoolExecutor.DiscardPolicy：也是丢弃任务，但是不抛出异常。
         * ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）
         * ThreadPoolExecutor.CallerRunsPolicy：由调用线程处理该任务
         **/
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        //执行初始化
        executor.afterPropertiesSet();
        return executor;
    }

    @Bean("customer2Properties")
    public Customer2CustomerTaskProperties getDuoDianTaskProperties() {
        return new Customer2CustomerTaskProperties();
    }

    @EqualsAndHashCode(callSuper = true)
    @ConfigurationProperties(prefix = "spring.task.first")
    @Data
    static class Customer2CustomerTaskProperties extends CustomerTaskExecutorBuilder.CustomerTaskExecutorProperties {
    }

}